package com.xiaoq.distribution.endpoint;

import com.alibaba.dubbo.config.annotation.Reference;
import com.mongodb.DuplicateKeyException;
import com.xiaoq.BaseEndpoint2B;
import com.xiaoq.apis.sites.ISitesApi;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.coms.util.ConstantUtil;
import com.xiaoq.coms.util.IdGenerator;
import com.xiaoq.coms.util.JsonUtil;
import com.xiaoq.distribution.entity.DistriTicketEntity;
import com.xiaoq.distribution.entity.DistributorEntity;
import com.xiaoq.distribution.entity.TicketOrderItemEntity;
import com.xiaoq.distribution.producer.DistributionPublish;
import com.xiaoq.distribution.service.IDistriTicketService;
import com.xiaoq.distribution.service.IDistributorService;
import com.xiaoq.distribution.service.ITicketOrderItemService;
import com.xiaoq.distribution.vo.OrderAdditionVo;
import com.xiaoq.distribution.vo.OrderDataVo;
import com.xiaoq.distribution.vo.OrderTicketRequestVo;
import com.xiaoq.order.entity.PayState;
import com.xiaoq.order.entity.ShopOrderEntity;
import com.xiaoq.order.entity.ShoppingItem;
import com.xiaoq.order.service.IShopOrderService;
import com.xiaoq.shop.entity.OrderState;
import com.xiaoq.shop.entity.SKUEntity;
import com.xiaoq.shop.service.ISKUService;
import com.xiaoq.sms.SendSMSUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by chenjh on 2018/5/25.
 */
@RestController
@RequestMapping(value = "/api/v1/distributor/orders")
@Api(tags={"分销商(订单)相关Api"})
public class DistributorOrderEndpoint extends BaseEndpoint2B {

    @Reference(interfaceClass=ISitesApi.class,check=false,version="1.0.0")
    private ISitesApi sitesApi;

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private IDistributorService distributorService;

    @Autowired
    private IDistriTicketService distriTicketService;

    @Autowired
    private ISKUService skuService;

    @Autowired
    private DistributionPublish distributionPublish;

    @Autowired
    private ITicketOrderItemService ticketOrderItemService;

    @Autowired
    private IShopOrderService shopOrderService;

    @Autowired
    private SendSMSUtil sendSMSUtil;

    @ApiOperation(value = "分销商提交订单, 应该返回状态码和message", notes = "分销商提交订单, 应该返回状态码和message")
    @ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "分销商提交订单, 应该返回状态码和message") })
    @PostMapping(value = "", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
    public ResponseEntity<?> addOrders(@RequestBody OrderAdditionVo orderAdditionVo, HttpServletRequest request) {

        String clientId = orderAdditionVo.getClientId();
        OrderDataVo orderDataVo = orderAdditionVo.getData();
        String ticketId = "";
        //根据clientid,ticketId 查询分销商信息，判断是否存在
        if(orderDataVo == null || (StringUtils.isAnyBlank(clientId, (ticketId = orderDataVo.getTicketId())))){
            return GenericResponse.ng("clientId,ticketId 不能为空");
        }

        DistributorEntity distributorEntity = distributorService.getDistributorByClientId(clientId);
        /*if(distributorEntity == null){
            return GenericResponse.ng("clientId为["+clientId+"]的分销商不存在");
        }

        if(!StringUtils.equals(distributorEntity.getIsAgree(), ConstantUtil.DISTRIBUTION_AGREEMENT)){
            return GenericResponse.ng("分销商暂时未签合同");
        }*/

        DistriTicketEntity distriTicketEntity = distriTicketService.getDistriTicket(distributorEntity.getId(), ticketId);
        /*if(distriTicketEntity == null){
            return GenericResponse.ng("分销商暂时未签签订具体的票务信息");
        }

        //TODO 验证签名
        String distriTicketStatus = StringUtils.defaultIfBlank(distriTicketEntity.getStatus(), "");

        Map<String, Object> signMap = new HashMap<>();
        signMap.put("cellphoneNumber", orderDataVo.getCellphoneNumber());
        signMap.put("idCardList", orderDataVo.getIdCardList());
        signMap.put("number", orderDataVo.getNumber());
        signMap.put("shopOrderId", orderDataVo.getShopOrderId());
        signMap.put("totalAmount", orderDataVo.getTotalAmount());
        signMap.put("travelDate", orderDataVo.getTravelDate());
        signMap.put("userRealName", orderDataVo.getUserRealName());
        signMap.put("ticketId", orderDataVo.getTicketId());
        signMap.put("clientId", distributorEntity.getClientId());
        signMap.put("secretKey", distributorEntity.getSecretKey());

        String expectSign = Signature.getSign4Distribution(signMap);
        if(!StringUtils.equals(expectSign, orderAdditionVo.getSign())){
            return GenericResponse.ng("加密错误");
        }


        switch (distriTicketStatus){
            case ConstantUtil.DISTRITICKET_4_VERIFY:
                return GenericResponse.ng("门票未审核");
            case ConstantUtil.DISTRITICKET_CANCEL_VERIFY:
                return GenericResponse.ng("门票取消授权");
            case ConstantUtil.DISTRITICKET_VERIFY_FAIL:
                return GenericResponse.ng("门票审核失败");
            case ConstantUtil.DISTRITICKET_VERIFY_SUCCESS:
                break;

            default:
                return GenericResponse.ng("门票审核状态失败");
        }*/

        /*Long beginSellerTime = distriTicketEntity.getDistriTicketStart();
        beginSellerTime = beginSellerTime == null ? 0 : beginSellerTime;
        Long endSellerTime = distriTicketEntity.getDistriTicketEnd();
        endSellerTime = endSellerTime == null ? 0 : endSellerTime;
        long now = System.currentTimeMillis();
        if(beginSellerTime < now){
            return GenericResponse.ng("分销起始日期未到， 暂时不能分销此票.");
        }
        if (endSellerTime < now){
            return GenericResponse.ng("分销日期已过期， 暂不能分销此票。 请联系景区重新签订分销票务");
        }*/


        Long authNum = distriTicketEntity.getAuthNum();
        authNum = authNum == null ? 0 : authNum;
        long commitAuthNum = distriTicketEntity.getCommitAuthNum();
        long refundAuthNum = distriTicketEntity.getRefundAuthNum();
        if(commitAuthNum - refundAuthNum > authNum){
            return GenericResponse.ng("已超过授权数量");
        }

        /**
         * private String shopOrderId;
         private long totalAmount;
         private int number;
         private String ticketId;
         private List<String> idCardList;
         private String cellphoneNumber;
         private String userRealName;
         private String travelDate;
         */
        //创建订单
        ShopOrderEntity shopOrderEntity = new ShopOrderEntity();
        shopOrderEntity.setId(idGenerator.nextId());
        shopOrderEntity.setShopOrderId(orderDataVo.getShopOrderId());
        shopOrderEntity.setTotalAmount(orderDataVo.getTotalAmount()/100.0);
        shopOrderEntity.setPayState(PayState.PAID.value());
        shopOrderEntity.setOrderState(OrderState.DELIVERIED.value());
        shopOrderEntity.setShopId(distriTicketEntity.getShopId());
        shopOrderEntity.setCellphoneNumber(orderDataVo.getCellphoneNumber());
        shopOrderEntity.setUserRealName(orderDataVo.getUserRealName());
        shopOrderEntity.setCreateTime(System.currentTimeMillis());
        shopOrderEntity.setNote(distriTicketEntity.getAgreementId());   //备注 存合同id
        shopOrderEntity.setOrderType(ConstantUtil.ORDER_TYPE_TICKET);
        shopOrderEntity.setUserDeleteFlag(ConstantUtil.NOT_DELETE_STATUS); //设置为未删除
        shopOrderEntity.setDistributorId(distributorEntity.getId());
        SKUEntity skuEntity = skuService.getTicketSkuById(ticketId);
        if(skuEntity == null || StringUtils.isBlank(skuEntity.getId())){
            return GenericResponse.ng("此商品不存在或者已下架");
        }

        ShoppingItem shoppingItem = new ShoppingItem();
        //TODO 时间格式转换
        shoppingItem.setTravelDate(123123123L);
        shoppingItem.setNumber(orderDataVo.getNumber());
        shoppingItem.setSkuCode(skuEntity.getSkuCode());
        shoppingItem.setSpuName(skuEntity.getSpuName());
        shoppingItem.setPrice(skuEntity.getPrice());
        shoppingItem.setSpecifications(skuEntity.getSpecifications());

        shopOrderEntity.setShoppingItems(Arrays.asList(shoppingItem));
        shopOrderService.saveShopOrder(shopOrderEntity);

        //
        List<OrderTicketRequestVo> orderTicketRequestList = new ArrayList<>();

        List<String> ticketCodeList = new ArrayList<>();

        //创建订单明细
        for(String idCard : orderDataVo.getIdCardList()){

            TicketOrderItemEntity ticketOrderItemEntity = new TicketOrderItemEntity();
            ticketOrderItemEntity.setShopOrderId(orderDataVo.getShopOrderId());
            String orderItemId = idGenerator.nextId();
            ticketOrderItemEntity.setId(orderItemId);
            ticketOrderItemEntity.setIdCard(idCard);
            ticketOrderItemEntity.setTicketId(ticketId);
            ticketOrderItemEntity.setShopOrderId(orderDataVo.getShopOrderId());
            ticketOrderItemEntity.setNumber(1);
            ticketOrderItemEntity.setDistributorId(distributorEntity.getId());
            ticketOrderItemEntity.setPayState(PayState.PAID.value());
            ticketOrderItemEntity.setOrderState(ConstantUtil.ORDER_TICKET_STATUS_HAVE_PAID);
            ticketOrderItemEntity.setPrePrice(distriTicketEntity.getPrePrice());
            ticketOrderItemEntity.setSettleStatus(ConstantUtil.SETTLE_STATUS_WAIT);

            //保存到数据库
            ticketOrderItemService.save(ticketOrderItemEntity);

            String ticketCode = Long.toHexString(System.nanoTime());
            //保存到数据库
            ticketOrderItemEntity.setTicketCode(ticketCode);  // ticketCode唯一索引
            try {
                ticketOrderItemService.save(ticketOrderItemEntity);
                ticketCodeList.add(ticketCode);
            }catch (DuplicateKeyException e){
                ticketCode = Long.toHexString(System.nanoTime());
                ticketOrderItemEntity.setTicketCode(ticketCode);
                ticketOrderItemService.save(ticketOrderItemEntity);
                ticketCodeList.add(ticketCode);
            }

            OrderTicketRequestVo orderTicketRequestVo = new OrderTicketRequestVo();
            orderTicketRequestVo.setDistriTicketId(distriTicketEntity.getId());
            orderTicketRequestVo.setTicketOrderItemId(orderItemId);
            orderTicketRequestList.add(orderTicketRequestVo);
        }

        //TODO 统一发码（短信），可能调用第三方发码平台（如智游宝等等），给用户发短信
        String ticketCodes = StringUtils.join(ticketCodeList, ",");
        /**
         * @param userName 取票人姓名
         * @param shopName 景区名称
         * @param ticketName 票的名称
         * @param ticketNum 票的数量
         * @param tourDate 出游日期 格式 "yyyy-MM-dd"
         * @param orderNum 订单号
         * @param teleNumber 取票人电话
         * @param ticketCode 电子票号，多个以","分割
         */
        sendSMSUtil.sendSMS4DistributionOrder(orderDataVo.getUserRealName(),"","",orderDataVo.getNumber()+"","",
                orderDataVo.getShopOrderId(),orderDataVo.getCellphoneNumber(),ticketCodes);

        //统一发消息异步计算票的结算价格
        for (OrderTicketRequestVo orderTicketRequestVo : orderTicketRequestList){
            distributionPublish.sendDistributionMsg(orderTicketRequestVo);
        }

        // 修改分销票的数量

        return GenericResponse.ok();
    }


    //获取卖品API
    @ApiOperation(value = "获取卖品API", notes = "获取卖品API")
    @ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "获取卖品API") })
    @PostMapping(value = "/tickets", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
    public ResponseEntity<?> getAllTickets(HttpServletRequest request) {
        String shopId = getShopId();
        Map<String, List<SKUEntity>> specification2SKUMap = skuService.getTicketSkuMap(shopId, null, ConstantUtil.SALE_STATE_ON);
        //需求将specification2SKUMap 转回
        return null;
    }

    //获取订单状态API
    @ApiOperation(value = "获取订单状态API", notes = "获取订单状态API")
    @ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "获取订单状态API") })
    @PostMapping(value = "/status", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
    public ResponseEntity<?> getOrderStatus(HttpServletRequest request) {

        return null;
    }

    //获取短信重发/转发API
    @ApiOperation(value = "获取短信重发/转发API", notes = "获取短信重发/转发API")
    @ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "获取短信重发/转发API") })
    @PostMapping(value = "/sms", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
    public ResponseEntity<?> getSendSms(HttpServletRequest request) {

        return null;
    }


    //获取退票API
    @ApiOperation(value = "获取退票API", notes = "获取退票API")
    @ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "获取退票API") })
    @PostMapping(value = "/refund", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
    public ResponseEntity<?> getRefundOrders(HttpServletRequest request) {

        return null;
    }


    /**
     * {
     "clientId": "N1007168348766605312",
     "data": {
     "cellphoneNumber": "18584580732",
     "idCardList": [
     "1234566"
     ],
     "number": 1,
     "shopOrderId": "shopOrderId001001001",
     "ticketId": "59fae826975f301cb02302c00",
     "totalAmount": 1200,
     "travelDate": "travelDate",
     "userRealName": "chenjh"
     },
     "sign": "string"
     }
     */

    //获取退票API
    @ApiOperation(value = "test1000", notes = "test1000")
    @ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "test1000") })
    @GetMapping(value = "/test1000", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
    public ResponseEntity<?> test1000(HttpServletRequest request,@RequestParam Integer orderCount,
                                      @RequestParam(required = false, name = "createdTime") Long createdTime) {

        int orderNum = orderCount==null?1000:orderCount;
        createdTime = createdTime == null?System.currentTimeMillis():createdTime;

        for (int i = 1; i<orderNum+1; i++){
            String json = "{\"clientId\":\"N1007168348766605312\",\"data\":{\"cellphoneNumber\":\"18584580732\",\"idCardList\":[\"1234566\"],\"number\":1,\"shopOrderId\":\"shopOrderId001001001\",\"ticketId\":\"59fae826975f301cb02302c00\",\"totalAmount\":1200,\"travelDate\":\"travelDate\",\"userRealName\":\"chenjh\"},\"sign\":\"string\"}";
            OrderAdditionVo orderAdditionVo = JsonUtil.asObject(json, OrderAdditionVo.class);

            orderAdditionVo.getData().setShopOrderId("shopOrderid" + String.format("%04d", i));

            String clientId = orderAdditionVo.getClientId();
            OrderDataVo orderDataVo = orderAdditionVo.getData();

            String ticketId = "";
            //根据clientid,ticketId 查询分销商信息，判断是否存在
            if(orderDataVo == null || (StringUtils.isAnyBlank(clientId, (ticketId = orderDataVo.getTicketId())))){
                return GenericResponse.ng("clientId,ticketId 不能为空");
            }

            DistributorEntity distributorEntity = distributorService.getDistributorByClientId(clientId);

            DistriTicketEntity distriTicketEntity = distriTicketService.getDistriTicket(distributorEntity.getId(), ticketId);

            Long authNum = distriTicketEntity.getAuthNum();
            authNum = authNum == null ? 0 : authNum;
            long commitAuthNum = distriTicketEntity.getCommitAuthNum();
            long refundAuthNum = distriTicketEntity.getRefundAuthNum();
            if(commitAuthNum - refundAuthNum > authNum){
                return GenericResponse.ng("已超过授权数量");
            }

            //创建订单
            ShopOrderEntity shopOrderEntity = new ShopOrderEntity();
            shopOrderEntity.setId(idGenerator.nextId());
            shopOrderEntity.setShopOrderId(orderDataVo.getShopOrderId());
            shopOrderEntity.setTotalAmount(orderDataVo.getTotalAmount()/100.0);
            shopOrderEntity.setPayState(PayState.PAID.value());
            shopOrderEntity.setOrderState(OrderState.DELIVERIED.value());
            shopOrderEntity.setShopId(distriTicketEntity.getShopId());
            shopOrderEntity.setCellphoneNumber(orderDataVo.getCellphoneNumber());
            shopOrderEntity.setUserRealName(orderDataVo.getUserRealName());
            shopOrderEntity.setCreateTime(System.currentTimeMillis());
            shopOrderEntity.setNote(distriTicketEntity.getAgreementId());   //备注 存合同id
            shopOrderEntity.setOrderType(ConstantUtil.ORDER_TYPE_TICKET);
            shopOrderEntity.setUserDeleteFlag(ConstantUtil.NOT_DELETE_STATUS); //设置为未删除
            shopOrderEntity.setDistributorId(distributorEntity.getId());
            SKUEntity skuEntity = skuService.getTicketSkuById(ticketId);
            if(skuEntity == null || StringUtils.isBlank(skuEntity.getId())){
                return GenericResponse.ng("此商品不存在或者已下架");
            }

            ShoppingItem shoppingItem = new ShoppingItem();
            //TODO 时间格式转换
            shoppingItem.setTravelDate(123123123L);
            shoppingItem.setNumber(orderDataVo.getNumber());
            shoppingItem.setSkuCode(skuEntity.getSkuCode());
            shoppingItem.setSpuName(skuEntity.getSpuName());
            shoppingItem.setPrice(skuEntity.getPrice());
            shoppingItem.setSpecifications(skuEntity.getSpecifications());

            shopOrderEntity.setShoppingItems(Arrays.asList(shoppingItem));
            shopOrderService.saveShopOrder(shopOrderEntity);

            //
            List<OrderTicketRequestVo> orderTicketRequestList = new ArrayList<>();
            //创建订单明细
            for(String idCard : orderDataVo.getIdCardList()){

                TicketOrderItemEntity ticketOrderItemEntity = new TicketOrderItemEntity();
                ticketOrderItemEntity.setShopOrderId(orderDataVo.getShopOrderId());
                String orderItemId = idGenerator.nextId();
                ticketOrderItemEntity.setId(orderItemId);
                ticketOrderItemEntity.setIdCard(idCard);
                ticketOrderItemEntity.setTicketId(ticketId);
                ticketOrderItemEntity.setShopOrderId(orderDataVo.getShopOrderId());
                ticketOrderItemEntity.setNumber(1);
                ticketOrderItemEntity.setPayState(PayState.PAID.value());
                ticketOrderItemEntity.setDistributorId(distributorEntity.getId());
                ticketOrderItemEntity.setOrderState(OrderState.DELIVERIED.value());
                ticketOrderItemEntity.setPrePrice(distriTicketEntity.getPrePrice());
                ticketOrderItemEntity.setSettleStatus(ConstantUtil.SETTLE_STATUS_WAIT);
                ticketOrderItemEntity.setCreateTime(createdTime);

                //保存到数据库.
                ticketOrderItemEntity.setTicketCode(Long.toHexString(System.nanoTime()));  // ticketCode唯一索引
                ticketOrderItemService.save(ticketOrderItemEntity);

                OrderTicketRequestVo orderTicketRequestVo = new OrderTicketRequestVo();
                orderTicketRequestVo.setDistriTicketId(distriTicketEntity.getId());
                orderTicketRequestVo.setTicketOrderItemId(orderItemId);
                orderTicketRequestList.add(orderTicketRequestVo);
            }

            //TODO 统一发码（短信），可能调用第三方发码平台（如智游宝等等），给用户发短信
            //统一发消息异步计算票的结算价格
            for (OrderTicketRequestVo orderTicketRequestVo : orderTicketRequestList){
                distributionPublish.sendDistributionMsg(orderTicketRequestVo);
            }
        }

        return GenericResponse.ok();
    }


}
